﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using DM4;
using sscore;
using DevExpress.XtraGrid.Views.Base;
using sscore.Utils;

namespace DM4Client
{
    public partial class FrmMain
    {
        #region Form Handlers
        
        private void DgGroupsFocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            RefreshOneGroup();
        }

        private void rbiRefreshProjectItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            RefreshGroups();
        }

        private void rbiEditProjectItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            AddEditGroup();
        }

        private void rbiAddProjectItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            AddEditGroup(false);
        }

        private void rbiDeleteProjectItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DeleteGroup();
        }
        #endregion Form Handlers
           
        private void AddEditGroup(bool edit = true)
        {
            DataRow drs = _fGroups.gvGroups.GetDataRow(_fGroups.gvGroups.FocusedRowHandle);
            if (edit && drs == null) return;

            int grpId = edit ? SysUtils.ConvertFromDBVal<int>(drs[CnGroups.GrpId]) : DM4Consts.DefaultNULLId;

            if (_fGroups.gvGroups.FocusedRowHandle == DevExpress.XtraGrid.GridControl.InvalidRowHandle && edit) return;

            using (AddEditForms.FrmAddEditGroup frmAddEdit = new AddEditForms.FrmAddEditGroup(grpId))
            {
                DialogResult dr = frmAddEdit.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    if (!edit)
                        grpId = frmAddEdit.Result.Result;

                    RefreshGroups(grpId);
                }
            }
        }

        private void DeleteGroup()
        {
            if (_fGroups.gvGroups.FocusedRowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
            {
                DataRow drs = _fGroups.gvGroups.GetDataRow(_fGroups.gvGroups.FocusedRowHandle);
                int grpId = SysUtils.ConvertFromDBVal<int>(drs[CnGroups.GrpId]);

                if (MessageBox.Show(this, String.Format("Delete project with id {0}?", grpId), "Delete project",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.No)
                    return;

                OperationResult or = DeleteGroup(grpId);

                if (or.Result != DM4Consts.Ok)
                    MessageBox.Show(this, or.Message, DmConsts.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                else
                    MessageBox.Show(this, "Project deleted", "Delete project", MessageBoxButtons.OK, MessageBoxIcon.Information);

                RefreshGroups();
            }
        }
        
        private void RefreshGroups(int grpId = DM4Consts.DefaultNULLId)
        {
            _fGroups.gvGroups.FocusedRowChanged -= DgGroupsFocusedRowChanged;

            try
            {
                int id = DM4Consts.DefaultNULLId;
                if (grpId == DM4Consts.DefaultNULLId)
                {

                    if (_fGroups.gvGroups.RowCount > 0)
                    {
                        DataRow drs = _fGroups.gvGroups.GetDataRow(_fGroups.gvGroups.FocusedRowHandle);
                        id = SysUtils.ConvertFromDBVal<int>(drs[CnGroups.GrpId]);
                    }
                }
                else
                    id = grpId;

                try
                {
                    _fGroups.dgGroups.DataSource = null;

                    XMLInfo xi = GetGroupList(IsAdmin);
                    DtGroups = XMLInfo.FillTable(xi, DtGroups);

                    _fGroups.dgGroups.DataMember = DtGroups.TableName;
                    _fGroups.dgGroups.DataSource = DtGroups;

                    _fGroups.gvGroups.BeginUpdate();
                    try
                    {
                        int rowHandle = _fGroups.gvGroups.LocateByValue(CnGroups.GrpId, id);
                        // exiting the loop if no row is found 
                        if (rowHandle != DevExpress.XtraGrid.GridControl.InvalidRowHandle)
                            _fGroups.gvGroups.FocusedRowHandle = rowHandle;
                        else
                            if (_fGroups.gvGroups.RowCount > 0)
                                _fGroups.gvGroups.MoveFirst();

                        RefreshOneGroup();

                        
                    }
                    finally
                    {
                        _fGroups.gvGroups.EndUpdate();
                    }

                    RefreshOneGroup();

                    UpdateMainControlsState();
                }
                catch (Exception ex)
                {
                    //SERVER IS DOWN!! NEED RECONNECT                    
                    WriteError(ex.Message);
                    LoginToService();
                }
            }
            finally
            {
                _fGroups.gvGroups.FocusedRowChanged += DgGroupsFocusedRowChanged;
            }
        }

        private void RefreshOneGroup()
        {
            //get datarow           
            int rowHandle = _fGroups.gvGroups.FocusedRowHandle;
            DataRow drs = _fGroups.gvGroups.GetDataRow(rowHandle);

            //fill group info table 
            ShowGroupInfo(drs);

            //get modules
            if ((drs != null))
                RefreshModulesList(SysUtils.ConvertFromDBVal<int>(drs[CnGroups.GrpId]));

            UpdateMainControlsState();
        }
        
        private void ShowGroupInfo(DataRow drs)
        {
            //fill group info table 
            dsInfo.Tables["dtGroupInfo"].Rows.Clear();

            if (drs == null) return;

            DataRow dr = dsInfo.Tables["dtGroupInfo"].NewRow();
            dr["Name"] = "Project Id";
            dr["Value"] = drs[CnGroups.GrpId];
            dsInfo.Tables["dtGroupInfo"].Rows.Add(dr);

            dr = dsInfo.Tables["dtGroupInfo"].NewRow();
            dr["Name"] = "Name";
            dr["Value"] = drs["grp_name"];
            dsInfo.Tables["dtGroupInfo"].Rows.Add(dr);

            dr = dsInfo.Tables["dtGroupInfo"].NewRow();
            dr["Name"] = "Description";
            dr["Value"] = drs["grp_description"];
            dsInfo.Tables["dtGroupInfo"].Rows.Add(dr);

            dr = dsInfo.Tables["dtGroupInfo"].NewRow();
            dr["Name"] = "Script";
            dr["Value"] = drs["scr_name"];
            dsInfo.Tables["dtGroupInfo"].Rows.Add(dr);

            dr = dsInfo.Tables["dtGroupInfo"].NewRow();
            dr["Name"] = "Home Directory";
            dr["Value"] = drs["grp_homedir"];
            dsInfo.Tables["dtGroupInfo"].Rows.Add(dr);

            dr = dsInfo.Tables["dtGroupInfo"].NewRow();
            dr["Name"] = "Date Created";
            dr["Value"] = drs["grp_creation_date"];
            dsInfo.Tables["dtGroupInfo"].Rows.Add(dr);

            dr = dsInfo.Tables["dtGroupInfo"].NewRow();
            dr["Name"] = "Author";
            dr["Value"] = drs["usr_fullname"];
            dsInfo.Tables["dtGroupInfo"].Rows.Add(dr);

            //read script text
            _stbGroupInfoScript.Text = drs["scr_text"].ToString();
        }

    }
}
